/*The MIT License

Copyright (c) <1/27/2011> <erick.difiore>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

package com.d4a5.mapping.esri
{
	
	import com.d4a5.mapping.core.IHighlightedObject;
	import com.d4a5.mapping.core.ISelectedObject;
	import com.d4a5.mapping.core.MapObjectStateContainer;
	import com.esri.ags.Graphic;
	import com.esri.ags.geometry.MapPoint;
	import com.esri.ags.layers.GraphicsLayer;
	import com.esri.ags.renderers.Renderer;
	import com.esri.ags.symbol.Symbol;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.events.FlexEvent;
	
	public class wmeGraphicsLayer extends GraphicsLayer
	{
		protected var _highlighted:MapObjectStateContainer;
		protected var _selected:MapObjectStateContainer;
		
		public var mouseWiggle:uint = 2;
		protected var _mouseWiggleData:MouseEvent;
		public var hoverDuration:uint = 30;
		protected var _hoverTimer:Timer;
		
		
		
		public var moveToTopOnHighlight:Boolean = true;
		public var moveToTopOnSelect:Boolean = true;
		
		
		protected var _renderer:wmeRenderer;
		
		public function wmeGraphicsLayer()
		{
			super();
			
			this.addEventListener(FlexEvent.UPDATE_COMPLETE , onUpdateComplete);
			
			this._highlighted = new MapObjectStateContainer(MapObjectStateContainer.typeIHighlightedObject);
			this._selected = new MapObjectStateContainer(MapObjectStateContainer.typeISelectedObject);
		
			this._hoverTimer = new Timer( this.hoverDuration , 0 );
			this._hoverTimer.addEventListener(TimerEvent.TIMER,onHoverTimerComplete );
			
			this._mouseWiggleData = new MouseEvent( MouseEvent.MOUSE_MOVE , true , false , 0 , 0  );
			
			
			this._renderer = new wmeRenderer();
		}
		
		
		protected function onUpdateComplete( event:Event ) : void {
			
			if( this.map ){
				
				if( this.highlightedSymbol ){
					this.map.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
					this.map.addEventListener(MouseEvent.ROLL_OUT,onMouseRollOut);
				}
				
				if( this.selectedSymbol ){
					this.map.addEventListener(MouseEvent.CLICK,onMouseClick);
				}
				
				this.removeEventListener( FlexEvent.UPDATE_COMPLETE , onUpdateComplete );
			}
		}
		
		override public function add(graphic:Graphic):String {
			if( graphic is wmeGraphic ){
				graphic.addEventListener( wmeGraphic.EVENT_HIGHLIGHT_TRUE , onGraphicHighlighted );
				graphic.addEventListener( wmeGraphic.EVENT_SELECT_TRUE , onGraphicSelected );
				graphic.addEventListener( wmeGraphic.EVENT_HIGHLIGHT_FALSE , onGraphicDeHighlighted );
				graphic.addEventListener( wmeGraphic.EVENT_SELECT_FALSE , onGraphicDeSelected );
			}
			return super.add( graphic );
		}
		override public function remove(graphic:Graphic):void {
			if( graphic is wmeGraphic ){
				graphic.removeEventListener( wmeGraphic.EVENT_HIGHLIGHT_TRUE , onGraphicHighlighted );
				graphic.removeEventListener( wmeGraphic.EVENT_SELECT_TRUE , onGraphicSelected );
				graphic.removeEventListener( wmeGraphic.EVENT_HIGHLIGHT_FALSE , onGraphicDeHighlighted );
				graphic.removeEventListener( wmeGraphic.EVENT_SELECT_FALSE , onGraphicDeSelected );
			}
			super.remove( graphic );
		}
		
		
		protected function onGraphicHighlighted( event:Event ) : void {
			if( this.moveToTopOnHighlight ){
				this.moveToTop( event.target as Graphic );
			}
			this._highlighted.addItem( event.target );
		}
		
		protected function onGraphicSelected( event:Event ) : void {
			if( this.moveToTopOnSelect ){
				this.moveToTop( event.target as Graphic );
			}
			this._selected.addItem( event.target );
		}
		
		protected function onGraphicDeHighlighted( event:Event ) : void {
			if( this.moveToTopOnHighlight ){
				if( event.target.selected == false ){
					this.moveToBottom( event.target as Graphic );
				}
			}
			
			this._highlighted.removeItem( event.target );
		}
		
		protected function onGraphicDeSelected( event:Event ) : void {
			if( this.moveToTopOnHighlight ){
				this.moveToBottom( event.target as Graphic );
			}
			this._selected.removeItem( event.target );
		}
		
		public function moveToBottom( g:Graphic ) : void {
			this.setChildIndex( g , 0 );
		}
		
		
		public function get multihighlight():Boolean {
			return this._highlighted.allowMultiples;
		}
		public function set multihighlight(value:Boolean):void {
			this._highlighted.allowMultiples = value;
		}
		public function get multiselect():Boolean {
			return this._selected.allowMultiples;
		}
		public function set multiselect(value:Boolean):void {
			this._selected.allowMultiples = value;
		}
		
		
		public function get highlighted() : MapObjectStateContainer {
			return this._highlighted;
		}
		public function get selected() : MapObjectStateContainer {
			return this._selected;
		}
		
		[Bindable]
		override public function get renderer():Renderer {
			return this._renderer;
		}
		override public function set renderer(value:Renderer):void {
			this._renderer.innerRenderer = value;
		}
		[Bindable]
		override public function get symbol():Symbol {
			return this._renderer.defaultSymbol;
		}
		override public function set symbol(value:Symbol):void {
			this._renderer.defaultSymbol = value;
		}
		
		[Bindable]
		public function get highlightedSymbol():Symbol {
			return this._renderer.highlightedSymbol;
		}
		public function set highlightedSymbol(value:Symbol):void {
			
			this._renderer.highlightedSymbol = value;
			if( this.map ){
				
				if( value ){
					this.map.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
					this.map.addEventListener(MouseEvent.ROLL_OUT,onMouseRollOut);
				}
				else{
					try{
						this.map.removeEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
						this.map.removeEventListener(MouseEvent.ROLL_OUT,onMouseRollOut);
					}
					catch( except:Object ){}
				}
			}
		}
		
		[Bindable]
		public function get selectedSymbol():Symbol {
			return this._renderer.selectedSymbol;
		}
		public function set selectedSymbol(value:Symbol):void {
			
			this._renderer.selectedSymbol = value;
			if( this.map ){
				
				if( value ){
					this.map.addEventListener(MouseEvent.CLICK,onMouseClick);
				}
				else{
					try{
						this.map.removeEventListener(MouseEvent.MOUSE_MOVE,onMouseClick);
					}
					catch( except:Object ){}
				}
			}
		}
		
		[Bindable]
		public function get bothSymbol():Symbol {
			return this._renderer.bothSymbol;
		}
		public function set bothSymbol(value:Symbol):void {
			this._renderer.bothSymbol = value;
		}
		
		
		protected function onMouseMove( event:MouseEvent ) : void {
			var currentPt:Point = new Point( event.stageX , event.stageY );
			
			var doSomething:Boolean = ( this.mouseWiggle == 0 || this.mouseWiggle < Point.distance( currentPt , new Point( this._mouseWiggleData.stageX , this._mouseWiggleData.stageY ) ) );
			
			if( doSomething ){
				this._mouseWiggleData = event;
				
				if( this.hoverDuration == 0 ){
					this.highlightGraphicsUnderPt( this._mouseWiggleData );
				}
				else{
					this._hoverTimer.stop();
					this._hoverTimer.delay = this.hoverDuration;
					this._hoverTimer.start();
				}
			}

		}
		
		protected function onHoverTimerComplete( event:TimerEvent ) : void {
			this._hoverTimer.stop();
			this.highlightGraphicsUnderPt( this._mouseWiggleData );
		}
		
		protected function highlightGraphicsUnderPt( ptData:MouseEvent ) : void {
			var gp:Array = this.graphicProvider.toArray();
			var gpLength:int = gp.length;
			var h:Object;
			
			if( this.multihighlight ){
				for( var j:int = 0; j < gpLength; j++ ){
					h = gp[j];
					if( h is IHighlightedObject ){
						h.highlighted = h.hitTestPoint( ptData.stageX , ptData.stageY , true );
						if( h.highlighted){
							trace( (h as wmeGraphic).attributes.name );
						}
					}
				}
			}
			else{
				var nearest:Object = {distSqr:Number.MAX_VALUE, graphic:null};
				
				for( var i:int = 0; i < gpLength; i++ ){
					h = gp[i];
					
					if( h is IHighlightedObject ){
						
						if( h.hitTestPoint( ptData.stageX , ptData.stageY , true ) ){
							var center:MapPoint = (h as Graphic).geometry.extent.center;
							var cX:Number = this.toScreenX( center.x );
							var cY:Number = this.toScreenY( center.y );
							var distSqr:Number = (cX - ptData.localX)*(cX - ptData.localX) + (cY - ptData.localY)*(cY - ptData.localY);
							
							if( distSqr < nearest.distSqr ){
								if( nearest.graphic ){
									nearest.graphic.highlighted = false;
								}
								nearest.graphic = h;
								nearest.distSqr = distSqr;
							}
							else{
								h.highlighted = false;
							}
						}
						else{
							h.highlighted = false;
						}
					}
				}
				
				if( nearest.graphic ){
					nearest.graphic.highlighted = true;
				}
				
				
			}
		}
		
		protected function onMouseRollOut( event:MouseEvent ) : void {
			this._highlighted.removeAll();
		}
		
		protected function onMouseClick( event:MouseEvent ) : void {
			this.selectGraphicsUnderPt ( event );
		}
		
		protected function selectGraphicsUnderPt( ptData:MouseEvent ) : void {
			var gp:Array = this.graphicProvider.toArray();
			var gpLength:int = gp.length;
			var s:Object;
			
			if( this.multiselect ){
				for( var j:int = 0; j < gpLength; j++ ){
					s = gp[j];
					if( s is ISelectedObject ){
						s.selected = ( s.hitTestPoint( ptData.stageX , ptData.stageY , true ) )
										? (( s.selected )
											? false : true)
										: (( s.selected )
											? true : false);
					}
				}
			}
			else{
				var nearest:Object = {distSqr:Number.MAX_VALUE, graphic:null};
				
				for( var i:int = 0; i < gpLength; i++ ){
					s = gp[i];
					if( s is ISelectedObject ){
						
						if( s.hitTestPoint( ptData.stageX , ptData.stageY , true ) ){
							var center:Point = ((s as wmeGraphic).geometry as Object).amf.bounds.center;
							var cX:Number = this.toScreenX( center.x );
							var cY:Number = this.toScreenY( center.y );
							var distSqr:Number = (cX - ptData.localX)*(cX - ptData.localX) + (cY - ptData.localY)*(cY - ptData.localY);
							
							if( distSqr < nearest.distSqr ){
								if( nearest.graphic ){
									nearest.graphic.selected = false;
								}
								nearest.graphic = s;
								nearest.distSqr = distSqr;
							}
							else{
								s.selected = false;
							}
						}
						else{
							s.selected = false;
						}
					}
				}
				
				if( nearest.graphic ){
					nearest.graphic.selected = true;
				}
				
				
			}
		}
		
	}
}